package com.pkk.cloud.support.oauth2.common.utils;

import com.pkk.components.moudle.oauth2.AuthServiceException;
import com.pkk.components.rpc.common.code.AuthoritiesCode;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.util.Base64Utils;

/**
 * @author peikunkun<br>
 * @version V1.0<br>
 * @Title: 客户端token的操作工具类<br>
 * @Description: <><br>
 * @date 2020/3/21 0021 下午 1:51<br>
 * @URL:[]
 */
public class ClientUtil {

  public static final String HEADER_AUTHORIZATION = "Authorization";
  public static final String BASIC_AUTH_PREFIX = "Basic ";

  /**
   * @Description: 提取token的信息[clientId:clientSecurity]
   * @Param: header
   * @return: java.lang.String[]
   * @Author: peikunkun
   * @Date: 2020/3/25 0025 下午 2:55
   */
  public static String[] extractAndDecodeHeader(String header) throws IOException {
    byte[] base64Token = header.substring(6).getBytes("UTF-8");

    byte[] decoded;
    try {
      decoded = Base64Utils.decode(base64Token);
    } catch (IllegalArgumentException var7) {
      throw new BadCredentialsException("Failed to decode basic authentication token");
    }

    String token = new String(decoded, "UTF-8");
    int delim = token.indexOf(":");
    if (delim == -1) {
      throw new BadCredentialsException("Invalid basic authentication token");
    } else {
      return new String[]{token.substring(0, delim), token.substring(delim + 1)};
    }
  }

  /**
   * @Description: 从请求头中获取客户端的信息
   * @Param: request
   * @return: java.lang.String
   * @Author: peikunkun
   * @Date: 2020/3/25 0025 下午 2:54
   */
  public static String getClientId(HttpServletRequest request) throws IOException {
    String header = request.getHeader(HEADER_AUTHORIZATION);
    if (header == null || !header.startsWith(BASIC_AUTH_PREFIX)) {
      throw new AuthServiceException(AuthoritiesCode.HEADER_INVALID_CLIENT_ERROR);
    }
    String[] tokens = extractAndDecodeHeader(header);
    assert tokens.length == 2;
    return tokens[0];
  }
}
